#include "./TimeController.h"
#include "../CommFormat.h"
#include <map>
#include <string.h>	//memcpy

void TimeController::ConnObjVR ()
{
	ClientSocket::conn(host, 2000);
}

bool TimeController::OnTime ()
{
	if ( --time_interval == 0 )
	{
		return true;
	}
	return false;
}

void TimeController::MsgSend ()
{
	*this << msg;
}

void* InstSendTimer (void* arg)
{
	struct in6_addr ipv6_addr;
	string buff = *(string*)arg;
	int buffsize = buff.size();
	cout << "recv time ctrl msg, size is: " << buffsize << endl;
	const int arrlen = buff[1];
	int pos, interval;
	char tmp_str[ADDR6STRLEN];
	string vr_addr_str, ctrlmsg;
	map<string, TimeController*> controllers;
	while (buffsize > 24)
	{
		interval = *(int*)(buff.substr(buffsize - 4)).c_str();
		memcpy(&ipv6_addr, (buff.substr(buffsize - 20, 16)).c_str(), 16);
		inet_ntop(AF_INET6, (void*)&ipv6_addr, tmp_str, sizeof(tmp_str));
		vr_addr_str = tmp_str;
		ctrlmsg = buff.substr(buffsize - 24, 4);
		buff.erase(buffsize - 24);
		buffsize -= 24;
		controllers[vr_addr_str] = new TimeController(vr_addr_str, ctrlmsg, interval);
	}
	
	struct timeval timer;
	time_t clock_value, clock_inter;
	fd_set fdset;
	int maxfdp1, slt, readfd;
	map<string, TimeController*>::iterator iter;
	while (true)
	{
		FD_ZERO(&fdset);
		int maxfd = 0;
		timer.tv_sec = 1;
		timer.tv_usec = 0;
		maxfdp1 = maxfd + 1;
		cout << controllers.size() << endl;
		select(maxfdp1, NULL, NULL, NULL, &timer);
		if (controllers.size()) 
		{
			for (iter = controllers.begin(); iter != controllers.end(); iter++)
			{
				if (iter->second->OnTime())
				{
					iter->second->ConnObjVR();
					iter->second->MsgSend();
					delete controllers[iter->first];
					controllers.erase(iter->first);
				}
			}
		}
		else
		{
			cout << "vlink time ctrl msg sent." << endl;
			break;
		}
	}
}

